<template>

  <div class="p-3">
    <el-scrollbar height="300px">
      <!-- 滑块控制段数 -->
      <el-slider class="p-5" v-model="segments" :step="1" show-stops :max="10" :marks="marks"/>

      <!-- 表格展示 -->
      <table class="table table-bordered table-hover">
        <thead>
        <tr>
          <th class="whitespace-nowrap">开始出力(MW)</th>
          <th class="whitespace-nowrap">结束出力(MW)</th>
          <th class="whitespace-nowrap">电价(元/MWh)</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, index) in dataList" :key="index">
          <td>
            <!-- 第一行的“开始出力(MW)”可编辑 -->
            <el-input
                v-model="row.startOutput"
                :disabled="index !== 0"
                @input="handleStartInput(index)"
            />
          </td>
          <td>
            <el-input
                v-model="row.endOutput"
                @blur="validateEndOutput(index)"
            />
          </td>
          <td>
            <el-input v-model="row.price" @input="emitUpdate"/>
          </td>
        </tr>
        </tbody>
      </table>
    </el-scrollbar>

  </div>
</template>

<script setup>
import {ref, watch} from "vue";
import {ElMessage} from "element-plus";

// 段数控制
const segments = ref(5);

// 表格数据
const dataList = ref([]);

const props = defineProps({
  dataList: Array,
});

const emit = defineEmits(["upDateDataList"]);

const emitUpdate = () => {
  emit("upDateDataList", dataList);
};

const marks = ref({
  0: '0',
  1: '1',
  2: '2',
  3: '3',
  4: '4',
  5: '5',
  6: '6',
  7: '7',
  8: '8',
  9: '9',
  10: '10'
})
// 监听 segments 变化，动态调整 dataList 的行数
watch(segments, (newVal) => {
  if (newVal > dataList.value.length) {
    // 增加新行
    while (dataList.value.length < newVal) {
      dataList.value.push({
        startOutput: dataList.value.length
            ? dataList.value[dataList.value.length - 1].endOutput || ""
            : "",
        endOutput: "",
        price: "",
      });
    }
  } else if (newVal < dataList.value.length) {
    // 删除多余行
    dataList.value.splice(newVal);
  }
}, {
  immediate: true
});

// 监听 dataList 变化
watch(props.dataList, (newVal) => {
  dataList.value = newVal;
});

// 处理“开始出力”逻辑
const handleStartInput = (index) => {
  if (index === 0) return; // 第一行无继承逻辑
  for (let i = index; i < dataList.value.length; i++) {
    dataList.value[i].startOutput =
        i > 0 ? dataList.value[i - 1].endOutput || "" : "";
  }
  emit("upDateDataList", dataList);
};

// 校验“结束出力”值，仅在用户完成输入后校验
const validateEndOutput = (index) => {
  const row = dataList.value[index];
  if (parseFloat(row.endOutput) < parseFloat(row.startOutput)) {
    ElMessage.error("结束出力不能小于开始出力！");
    // 自动纠正为开始出力
    row.endOutput = row.startOutput;
  }

  // 自动更新下一行的开始出力
  if (index < dataList.value.length - 1) {
    dataList.value[index + 1].startOutput = row.endOutput || "";
  }
};
</script>
<style>
.el-slider__marks-text {
  top: -35px;
}
</style>